package com.hskn.hss.module.alarmsheshi.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hskn.hss.core.annotation.DataScope;
import com.hskn.hss.core.domain.BaseEntity;
import com.hskn.hss.core.page.TableDataInfo;
import com.hskn.hss.core.utils.LoginUtils;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.alarmHandleLog.domain.AlarmHandleLog;
import com.hskn.hss.module.alarmHandleLog.service.IAlarmHandleLogService;
import com.hskn.hss.module.alarmperson.entity.AlarmPerson;
import com.hskn.hss.module.alarmsheshi.entity.AlarmSheshi;
import com.hskn.hss.module.alarmsheshi.entity.AlarmSheshiCharts;
import com.hskn.hss.module.alarmsheshi.mapper.AlarmSheshiMapper;
import com.hskn.hss.module.alarmsheshi.service.IAlarmSheshiService;
import com.hskn.hss.module.alarmsheshi.vo.AlarmSheshiTableDetailVO;
import com.hskn.hss.module.depart.entity.SysDepart;
import com.hskn.hss.module.depart.mapper.SysDepartMapper;
import com.hskn.hss.module.depart.service.ISysDepartService;
import com.hskn.hss.module.dlbjviolation.entity.DlbjViolation;
import com.hskn.hss.module.messageFlowRecords.domain.MessageFlowRecords;
import com.hskn.hss.module.messageFlowRecords.service.IMessageFlowRecordsService;
import com.hskn.hss.module.tlfacilities.entity.TlFacilities;
import com.hskn.hss.module.tlfacilities.mapper.TlFacilitiesMapper;
import com.hskn.hss.module.tlfacilities.service.ITlFacilitiesService;
import com.hskn.hss.module.tlfacilitietype.entity.TlFacilitiesType;
import com.hskn.hss.module.tlfacilitietype.mapper.TlFacilitiesTypeMapper;
import com.hskn.hss.module.user.entity.User;
import com.hskn.hss.module.user.mapper.UserMapper;
import com.hskn.hss.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hskn
 * @since 2021-05-21
 */
@Slf4j
@Service
public class AlarmSheshiServiceImpl extends ServiceImpl<AlarmSheshiMapper, AlarmSheshi> implements IAlarmSheshiService {

    @Resource
    private AlarmSheshiMapper alarmSheshiMapper;
    @Resource
    private SysDepartMapper sysDepartMapper;
    @Resource
    private TlFacilitiesMapper facilitiesMapper;
    @Resource
    private TlFacilitiesTypeMapper facilitiesTypeMapper;
    @Autowired
    private IAlarmHandleLogService alarmHandleLogService;
    @Resource
    private UserMapper userMapper;
    @Autowired
    private ITlFacilitiesService facilitiesService;
    @Autowired
    private IMessageFlowRecordsService messageFlowRecordsService;
    @Autowired
    LocationUtils locationUtil;
    @Autowired
    ISysDepartService departService;

    @Override
    @DataScope(deptAlias = "dep_id", userAlias = "deal_uid")
    public JSONObject mList(BaseEntity entity, JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        JSONObject json = new JSONObject();
        QueryWrapper<AlarmSheshi> queryWrapper = new QueryWrapper<>();
        if (entity.getParams().containsKey("dataScope")&&StringUtils.isNotEmpty(entity.getParams().get("dataScope"))) {
            queryWrapper.lambda().apply(entity.getParams().get("dataScope").toString());
        }
        String alarmSheshiId = params.getString("alarmSheshiId");
        if (StringUtils.isNotEmpty(alarmSheshiId)) {
            queryWrapper.lambda().eq(AlarmSheshi::getAlarmSheshiId,alarmSheshiId);
        }
        String sheshiId = params.getString("sheshiId");
        if (StringUtils.isNotEmpty(sheshiId)) {
            queryWrapper.lambda().eq(AlarmSheshi::getSheshiId,sheshiId);
        }
        String alarmTypeId = params.getString("alarmTypeId");
        if (StringUtils.isNotEmpty(alarmTypeId)) {
            queryWrapper.lambda().eq(AlarmSheshi::getAlarmTypeId,alarmTypeId);
        }
        String alarmTypeName = params.getString("alarmTypeName");
        if (StringUtils.isNotEmpty(alarmTypeName)) {
            queryWrapper.lambda().eq(AlarmSheshi::getAlarmTypeName,alarmTypeName);
        }
        String startDate = params.getString("startDate");
        String endDate = params.getString("endDate");
        if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate)) {
            queryWrapper.lambda().between(AlarmSheshi::getAlarmTime,startDate + " 00:00:00",endDate + " 23:59:59");
        }
        String facilitiesTypeId = params.getString("facilitiesTypeId");
        if (StringUtils.isNotEmpty(facilitiesTypeId)) {
            queryWrapper.lambda().eq(AlarmSheshi::getFacltypeid,facilitiesTypeId);
        }
        String facilitiesTypeItemsId = params.getString("facilitiesTypeItemsId");
        if (StringUtils.isNotEmpty(facilitiesTypeItemsId)) {
            queryWrapper.lambda().eq(AlarmSheshi::getFacltypeitemid,facilitiesTypeItemsId);
        }
        String sheShiNames = params.getString("sheShiName");
        if (StringUtils.isNotEmpty(sheShiNames)) {
            sheShiNames = "('" + sheShiNames.replace(",", "','") + "')";
            queryWrapper.lambda().in(AlarmSheshi::getSheshiName,sheShiNames);
        }
        Long page = StringUtils.isEmpty(params.getLong("page")) || params.getLong("page") < 0 ? 0 : params.getLong("page");
        Long size = StringUtils.isEmpty(params.getLong("size")) ? 10 : params.getLong("size");

        queryWrapper.lambda().orderByDesc(AlarmSheshi::getCreateTime);
        Page<AlarmSheshi> listPage = new Page<>(page, size, true);
        Page<AlarmSheshi> resultList = alarmSheshiMapper.selectPage(listPage,queryWrapper);
//        Page<Map<String, Object>> resultList = alarmSheshiMapper.mySelectPage(listPage,map);
        Map<String,TlFacilities> facilitiesMap=facilitiesService.getFacMap(new QueryWrapper<>());
        List<AlarmSheshi> list=listPage.getRecords();
        for(AlarmSheshi alarmSheshi:list){
            if(facilitiesMap.containsKey(alarmSheshi.getSheshiId())){
                alarmSheshi.setFacHeadPortraitAlarm(facilitiesMap.get(alarmSheshi.getSheshiId()).getFileurl());
            }
            MessageFlowRecords messageFlowRecords = new MessageFlowRecords();
            messageFlowRecords.setMessageId(alarmSheshi.getAlarmSheshiId());
            messageFlowRecords.setKind(1);
            messageFlowRecords.setSubjectType(3);
            messageFlowRecords.setUserId(uid);
            List<MessageFlowRecords> messageFlowRecords1 = messageFlowRecordsService.selectMessageFlowRecordsList(messageFlowRecords);
            if ((Objects.nonNull(messageFlowRecords1) && messageFlowRecords1.size() > 0) || alarmSheshi.getAlarmTime().compareTo(DateUtil.parseDateTime(AttributeUtils.timeCompletion(DateUtil.formatDate(new Date()), 's'))) < 0){
                alarmSheshi.setIsRead(1);
            } else {
                alarmSheshi.setIsRead(0);
            }
        }
        json.put("total", resultList.getTotal());
        json.put("size", resultList.getSize());
        json.put("pages", resultList.getPages());
        json.put("list", resultList.getRecords());
        return json;
    }


    @Override
    public JSONObject getAbnormal() {

        JSONObject result = new JSONObject();

        String day = DateUtil.formatDate(new Date());
        String startTime = AttributeUtils.timeCompletion(day, 's');
        String endTime = AttributeUtils.timeCompletion(day, 'e');

        QueryWrapper<AlarmSheshi> alarmSheshiQueryWrapper = new QueryWrapper<>();
        alarmSheshiQueryWrapper.lambda().ge(AlarmSheshi::getAlarmTime,startTime);
        alarmSheshiQueryWrapper.lambda().le(AlarmSheshi::getAlarmTime,endTime);
        List<AlarmSheshi> alarmSheshis = alarmSheshiMapper.selectList(alarmSheshiQueryWrapper);

        //设施报警
        Map<String, Long> alarmSheshiMap = alarmSheshis.stream().collect(Collectors.groupingBy(AlarmSheshi::getAlarmTypeName, Collectors.counting()));

        Map<String,Long> facilityAlarmMap = new HashMap();
        facilityAlarmMap.put("烟雾报警",0L);
        facilityAlarmMap.put("氨气报警",0L);
        facilityAlarmMap.put("硫化氢报警",0L);
        facilityAlarmMap.put("开盖报警",0L);
        facilityAlarmMap.put("水位超限",0L);
        alarmSheshiMap.keySet().forEach(t->{
            if ("烟雾报警".equals(t)){
                facilityAlarmMap.put("烟雾报警",alarmSheshiMap.get(t));
            } else if ("氨气报警".equals(t)){
                facilityAlarmMap.put("氨气报警",alarmSheshiMap.get(t));
            } else if ("硫化氢报警".equals(t)){
                facilityAlarmMap.put("硫化氢报警",alarmSheshiMap.get(t));
            } else if ("开盖报警".equals(t)){
                facilityAlarmMap.put("开盖报警",alarmSheshiMap.get(t));
            } else if ("水位超限".equals(t)){
                facilityAlarmMap.put("水位超限",alarmSheshiMap.get(t));
            }
        });

        // 转list
        List<Map.Entry<String,Long>> facilityAlarmList = new ArrayList<>(facilityAlarmMap.entrySet());
        facilityAlarmList.sort(Comparator.comparing(Map.Entry::getValue));
        //排序
        Collections.sort(facilityAlarmList, (o1, o2) -> {
            Long d1 = o1.getValue();
            Long d2 = o2.getValue();
            return d2.compareTo(d1);
        });

        //格式化list
        List<String> alarmSheshiList = new ArrayList<>();
        facilityAlarmList.forEach(t->{
            alarmSheshiList.add(t.getKey() + ":" + t.getValue());
        });

        result.put("facilityAlarmNum", alarmSheshis.size());
        result.put("facilityAlarmList", alarmSheshiList);

        return result;
    }

    @Override
    public void deal(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        if (StringUtils.isEmpty(params) || StringUtils.isEmpty(params.getString("alarmSheshiIds"))) {
            throw new HssException("参数错误");
        }
        String alarmSheshiIdStr = params.getString("alarmSheshiIds");
        String[] alarmSheshiIds = alarmSheshiIdStr.split(",");
        QueryWrapper<AlarmSheshi> alarmCarQueryWrapper=new QueryWrapper<>();
        alarmCarQueryWrapper.lambda().in(AlarmSheshi::getAlarmSheshiId,alarmSheshiIds);
        List<AlarmSheshi> alarmCarList=alarmSheshiMapper.selectList(alarmCarQueryWrapper);
        User user=userMapper.selectById(uid);
        Map<String,AlarmSheshi> alarmSheshiMap=null;
        if(!alarmCarList.isEmpty()){
            alarmSheshiMap= GroupingByUtils.getGroupingForMapEntity(alarmCarList,AlarmSheshi::getAlarmSheshiId
                    , Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));
        }else {
            alarmSheshiMap=new HashMap<>();
        }
        List<AlarmSheshi> alarmSheshis = new ArrayList<>();
        AlarmSheshi aalarmSheshi=null;
        AlarmHandleLog alarmHandleLog= null;
        List<AlarmHandleLog> alarmHandleLogList=new LinkedList<>();
        for (String alarmSheshiId : alarmSheshiIds) {
            AlarmSheshi alarmSheshi = new AlarmSheshi(alarmSheshiId, params.getString("dealType"), params.getString("dealRemark"), uid);
            alarmSheshis.add(alarmSheshi);
            if(alarmSheshiMap.containsKey(alarmSheshiId)){
                aalarmSheshi=alarmSheshiMap.get(alarmSheshiId);
                alarmHandleLog =getAlarmHandleLog(aalarmSheshi,params,uid,user);
                alarmHandleLogList.add(alarmHandleLog);
            }
        }
        alarmHandleLogService.saveBatch(alarmHandleLogList);
        updateBatchById(alarmSheshis);
    }
    private AlarmHandleLog getAlarmHandleLog(AlarmSheshi alarmCar , JSONObject params, String uid , User user){
        AlarmHandleLog alarmHandleLog=new AlarmHandleLog(StringUtils.uuid(),alarmCar.getAlarmSheshiId(),alarmCar.getSheshiId(),alarmCar.getSheshiName(),alarmCar.getFacltypeid(),alarmCar.getFacltypename(),
                new Date(),alarmCar.getDepId(),alarmCar.getDepName(),alarmCar.getAlarmTypeId(),alarmCar.getAlarmTypeName(), params.getString("dealType"),uid,user!=null?user.getName():"",
                params.getString("dealRemark"),alarmCar.getContent(),alarmCar.getAlarmStartTime(),alarmCar.getAlarmEndTime(),alarmCar.getIsKeep(),alarmCar.getLng(),alarmCar.getLat(),
                alarmCar.getAlarmTime(),alarmCar.getAddress(),"0","fac"

        );
        return alarmHandleLog;
    }
    @Override
    public JSONObject getSheshiPolice(JSONObject params) throws HssException {
        JSONObject json = new JSONObject();
        QueryWrapper<AlarmSheshi> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNotNull("alarm_type_name");
        queryWrapper.select("alarm_type_name");
        if (params != null) {
            if (StringUtils.isNotEmpty(params.getString("type")) && params.getString("type") != null) {
                queryWrapper.lambda().eq(AlarmSheshi::getAlarmTypeId, params.getString("type"));
            }
            if (StringUtils.isNotEmpty(params.getString("beginTime")) && params.getString("beginTime") != null && StringUtils.isNotEmpty(params.getString("endTime")) && params.getString("endTime") != null) {
                queryWrapper.lambda().between(AlarmSheshi::getCreateTime, params.getString("beginTime"), params.getString("endTime"));
            }
        }
        queryWrapper.lambda().groupBy(AlarmSheshi::getAlarmTypeName);
        List<Object> legendData = this.listObjs(queryWrapper);
        json.put("legendData", legendData);

        QueryWrapper<AlarmSheshi> queryWrapperx = new QueryWrapper<>();
        queryWrapperx.isNotNull("sheshi_name");
        queryWrapperx.select("sheshi_name");
        if (params != null) {
            if (StringUtils.isNotEmpty(params.getString("persionId")) && params.getString("persionId") != null) {
                queryWrapperx.lambda().eq(AlarmSheshi::getSheshiId, params.getString("persionId"));
            }
            if (StringUtils.isNotEmpty(params.getString("beginTime")) && params.getString("beginTime") != null && StringUtils.isNotEmpty(params.getString("endTime")) && params.getString("endTime") != null) {
                queryWrapperx.lambda().between(AlarmSheshi::getCreateTime, params.getString("beginTime"), params.getString("endTime"));
            }
        }
        queryWrapperx.lambda().groupBy(AlarmSheshi::getSheshiName);
        List<Object> xAxisData = this.listObjs(queryWrapperx);
        json.put("xAxisData", xAxisData);

        QueryWrapper<AlarmSheshi> queryWrappers = new QueryWrapper<>();
        queryWrappers.select("sheshi_name as xAxisData,alarm_type_name as legendData,count(1) as data");
        if (params != null) {
            if (StringUtils.isNotEmpty(params.getString("type")) && params.getString("type") != null) {
                queryWrappers.lambda().eq(AlarmSheshi::getAlarmTypeId, params.getString("type"));
            }
            if (StringUtils.isNotEmpty(params.getString("persionId")) && params.getString("persionId") != null) {
                queryWrappers.lambda().eq(AlarmSheshi::getSheshiId, params.getString("persionId"));
            }
            if (StringUtils.isNotEmpty(params.getString("beginTime")) && params.getString("beginTime") != null && StringUtils.isNotEmpty(params.getString("endTime")) && params.getString("endTime") != null) {
                queryWrappers.lambda().between(AlarmSheshi::getCreateTime, params.getString("beginTime"), params.getString("endTime"));
            }
        }
        queryWrappers.lambda().groupBy(AlarmSheshi::getSheshiId, AlarmSheshi::getSheshiName, AlarmSheshi::getAlarmTypeName);
        List<Map<String, Object>> alarms = this.listMaps(queryWrappers);
        List<Map<String, List>> seriesData = new ArrayList<Map<String, List>>();
        if (!legendData.isEmpty() && legendData != null) {
            for (Object legendDatas : legendData) {
                List list = new ArrayList();
                for (Map<String, Object> alarm : alarms) {
                    if (alarm.get("legendData") != null) {
                        if (alarm.get("legendData").equals(legendDatas)) {
                            list.add(alarm.get("data"));
                        } else {
                            if (!this.iset(alarms, legendDatas, alarm.get("xAxisData"))) {
                                list.add(0);
                            }
                        }
                    }
                }
                Map<String, List> map = new HashMap<String, List>();
                map.put(legendDatas.toString(), list);
                seriesData.add(map);
            }
        }
        json.put("seriesData", seriesData);
        return json;
    }

    private boolean iset(List<Map<String, Object>> alarms, Object legendData, Object xAxisData) {
        for (Map<String, Object> alarm : alarms) {
            if (alarm.get("legendData") != null && alarm.get("xAxisData") != null) {
                if (alarm.get("legendData").equals(legendData) && alarm.get("xAxisData").equals(xAxisData)) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public JSONObject collectList(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        JSONObject res = new JSONObject();
        Long page = (StringUtils.isEmpty(params.getLong("page")) || params.getLong("page") == 0) ? 1 : params.getLong("page");
        Long size = (StringUtils.isEmpty(params.getLong("size")) || params.getLong("size") == 0) ? 10 : params.getLong("size");
        params.put("offset", (page - 1) * size);
        params.put("limit", size);
        List<Map<String, Object>> list = alarmSheshiMapper.collectList(params);
        long count = alarmSheshiMapper.collectListCount(params);
        res.put("list", list);
        res.put("total", count);
        res.put("current", page);
        res.put("pages", (int) Math.ceil(count / size));
        res.put("size", list.size());
        return res;
    }
    @Override
    public List<List<Object>> selectAlarmSheshiForCharts(AlarmSheshi alarmSheshi) throws ParseException {
        if (Objects.isNull(alarmSheshi.getAlarmStartTime())){
            alarmSheshi.setAlarmStartTime(DateUtil.parseDateTime(DateUtil.format(new Date(), DatePattern.NORM_MONTH_PATTERN)+"-01 00:00:00"));
        } else {
            alarmSheshi.setAlarmStartTime(DateUtil.parseDateTime(DateUtil.formatDate(alarmSheshi.getAlarmStartTime()) +" 00:00:00"));
        }
        if (Objects.isNull(alarmSheshi.getAlarmEndTime())){
            alarmSheshi.setAlarmEndTime(DateUtil.parseDateTime(DateUtil.formatDate(new Date())+" 23:59:59"));
        } else {
            alarmSheshi.setAlarmEndTime(DateUtil.parseDateTime(DateUtil.formatDate(alarmSheshi.getAlarmEndTime())+" 23:59:59"));
        }
        Date startDate = alarmSheshi.getAlarmStartTime();
        Date endDate = alarmSheshi.getAlarmEndTime();

        List<AlarmSheshiCharts> bTableList= alarmSheshiMapper.selectAlarmSheshiForCharts(alarmSheshi);

        if (Objects.nonNull(bTableList) && bTableList.size()>0){
            QueryWrapper<AlarmSheshi> alarmCarQueryWrapper=new QueryWrapper<>();
            if (StringUtils.isNotEmpty(alarmSheshi.getSheshiName())){
                alarmCarQueryWrapper.lambda().eq(AlarmSheshi::getSheshiName,alarmSheshi.getSheshiName());
            }
            if (StringUtils.isNotEmpty(alarmSheshi.getFacltypeid())){
                alarmCarQueryWrapper.lambda().eq(AlarmSheshi::getFacltypeid,alarmSheshi.getFacltypeid());
            }
            if (StringUtils.isNotEmpty(alarmSheshi.getAlarmTypeId())){
                alarmCarQueryWrapper.lambda().eq(AlarmSheshi::getAlarmTypeId,alarmSheshi.getAlarmTypeId());
            }
            if (StringUtils.isNotEmpty(alarmSheshi.getAlarmTypeName())){
                alarmCarQueryWrapper.lambda().eq(AlarmSheshi::getAlarmTypeName,alarmSheshi.getAlarmTypeName());
            }
            if (StringUtils.isNotEmpty(alarmSheshi.getDepId())) {
                alarmCarQueryWrapper.lambda().in(AlarmSheshi::getDepId, alarmSheshi.getDepIds());
            }
            if ("2".equals(alarmSheshi.getDateType())){
                alarmCarQueryWrapper.lambda().ge(AlarmSheshi::getAlarmTime,bTableList.get(0).getAlarmTime() + "-01 00:00:00");
                alarmCarQueryWrapper.lambda().le(AlarmSheshi::getAlarmTime,bTableList.get(bTableList.size()-1).getAlarmTime() + "-31 23:59:59");
            } else {
                alarmCarQueryWrapper.lambda().ge(AlarmSheshi::getAlarmTime,bTableList.get(0).getAlarmTime() + " 00:00:00");
                alarmCarQueryWrapper.lambda().le(AlarmSheshi::getAlarmTime,bTableList.get(bTableList.size()-1).getAlarmTime() + " 23:59:59");
            }

            List<AlarmSheshi> alarmSheshiList = alarmSheshiMapper.selectList(alarmCarQueryWrapper);

            if ("2".equals(alarmSheshi.getDateType())){
                alarmSheshiList.forEach(t->{
                    t.setAlarmDate(DateUtil.format(t.getAlarmTime(),DatePattern.NORM_MONTH_PATTERN));
                });
            } else {
                alarmSheshiList.forEach(t->{
                    t.setAlarmDate(DateUtil.formatDate(t.getAlarmTime()));
                });
            }
            Map<String, List<AlarmSheshi>> alarmSheshiMap = alarmSheshiList.stream().collect(Collectors.groupingBy(AlarmSheshi::getAlarmDate));

            Map<String, Map<String, List<AlarmSheshi>>> map2 = new HashMap<>();
            alarmSheshiMap.keySet().forEach(t->{
                List<AlarmSheshi> alarmSheshis = alarmSheshiMap.get(t);
                Map<String, List<AlarmSheshi>> alarmTypeSheshiMap = alarmSheshis.stream().collect(Collectors.groupingBy(AlarmSheshi::getAlarmTypeName));
                map2.put(alarmSheshis.get(0).getAlarmDate(),alarmTypeSheshiMap);
            });

            for (AlarmSheshiCharts alarmSheshiCharts:bTableList
            ) {
                if (Objects.nonNull(map2.get(alarmSheshiCharts.getAlarmTime()).get("氨气报警"))){
                    alarmSheshiCharts.setNH4Count(map2.get(alarmSheshiCharts.getAlarmTime()).get("氨气报警").size());
                }
                if (Objects.nonNull(map2.get(alarmSheshiCharts.getAlarmTime()).get("烟雾报警"))){
                    alarmSheshiCharts.setSmokeCount(map2.get(alarmSheshiCharts.getAlarmTime()).get("烟雾报警").size());
                }
                if (Objects.nonNull(map2.get(alarmSheshiCharts.getAlarmTime()).get("硫化氢报警"))){
                    alarmSheshiCharts.setH2SCount(map2.get(alarmSheshiCharts.getAlarmTime()).get("硫化氢报警").size());
                }
            }
        }

        if ("2".equals(alarmSheshi.getDateType())){
            return getSelectAlarmForChartsByMonth(startDate, endDate, bTableList);
        } else {
            return getSelectAlarmForCharts(startDate, endDate, bTableList);
        }
    }
    @Override
    public List<AlarmSheshiCharts> selectAlarmSheshiForChartsTable(AlarmSheshi alarmSheshi){
        if (Objects.isNull(alarmSheshi.getAlarmStartTime())){
            alarmSheshi.setAlarmStartTime(DateUtil.parseDateTime(DateUtil.format(new Date(), DatePattern.NORM_MONTH_PATTERN)+"-01 00:00:00"));
        } else {
            alarmSheshi.setAlarmStartTime(DateUtil.parseDateTime(DateUtil.formatDate(alarmSheshi.getAlarmStartTime()) +" 00:00:00"));
        }
        if (Objects.isNull(alarmSheshi.getAlarmEndTime())){
            alarmSheshi.setAlarmEndTime(DateUtil.parseDateTime(DateUtil.formatDate(new Date())+" 23:59:59"));
        } else {
            alarmSheshi.setAlarmEndTime(DateUtil.parseDateTime(DateUtil.formatDate(alarmSheshi.getAlarmEndTime())+" 23:59:59"));
        }
        List<AlarmSheshiCharts> alarmSheshiChartsList=alarmSheshiMapper.selectAlarmSheshiForChartsTable(alarmSheshi);
        List<SysDepart> sysDepartList=sysDepartMapper.selectList(new QueryWrapper<>());
        List<TlFacilities> facilities=facilitiesMapper.selectList(new QueryWrapper<>());
        List<TlFacilitiesType> facilitieTypes=facilitiesTypeMapper.selectList(new QueryWrapper<>());
        Map<String,SysDepart> depMap=GroupingByUtils.getGroupingForMapEntity(sysDepartList,SysDepart::getId,Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));
        Map<String,TlFacilities> facMap=GroupingByUtils.getGroupingForMapEntity(facilities,TlFacilities::getId,Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));
        Map<String,TlFacilitiesType> facilitiesTypeMap=GroupingByUtils.getGroupingForMapEntity(facilitieTypes,TlFacilitiesType::getId,Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));

        if (Objects.nonNull(alarmSheshiChartsList) && alarmSheshiChartsList.size()>0){
            QueryWrapper<AlarmSheshi> alarmCarQueryWrapper=new QueryWrapper<>();
            if (StringUtils.isNotEmpty(alarmSheshi.getSheshiName())){
                alarmCarQueryWrapper.lambda().eq(AlarmSheshi::getSheshiName,alarmSheshi.getSheshiName());
            }
            if (StringUtils.isNotEmpty(alarmSheshi.getFacltypeid())){
                alarmCarQueryWrapper.lambda().eq(AlarmSheshi::getFacltypeid,alarmSheshi.getFacltypeid());
            }
            if (StringUtils.isNotEmpty(alarmSheshi.getAlarmTypeId())){
                alarmCarQueryWrapper.lambda().eq(AlarmSheshi::getAlarmTypeId,alarmSheshi.getAlarmTypeId());
            }
            if (StringUtils.isNotEmpty(alarmSheshi.getAlarmTypeName())){
                alarmCarQueryWrapper.lambda().eq(AlarmSheshi::getAlarmTypeName,alarmSheshi.getAlarmTypeName());
            }

            alarmCarQueryWrapper.lambda().ge(AlarmSheshi::getAlarmTime,alarmSheshi.getAlarmStartTime());
            alarmCarQueryWrapper.lambda().le(AlarmSheshi::getAlarmTime,alarmSheshi.getAlarmEndTime());

            List<AlarmSheshi> alarmSheshiList = alarmSheshiMapper.selectList(alarmCarQueryWrapper);

            alarmSheshiList.forEach(t->{
                t.setAlarmDate(DateUtil.formatDate(t.getAlarmTime()));
            });
            Map<String, List<AlarmSheshi>> alarmSheshiMap = alarmSheshiList.stream().collect(Collectors.groupingBy(AlarmSheshi::getSheshiName));

            Map<String, Map<String, List<AlarmSheshi>>> map2 = new HashMap<>();
            alarmSheshiMap.keySet().forEach(t->{
                List<AlarmSheshi> alarmSheshis = alarmSheshiMap.get(t);
                Map<String, List<AlarmSheshi>> alarmTypeSheshiMap = alarmSheshis.stream().collect(Collectors.groupingBy(AlarmSheshi::getAlarmTypeName));
                map2.put(alarmSheshis.get(0).getSheshiName(),alarmTypeSheshiMap);
            });

            for (AlarmSheshiCharts alarmSheshiCharts:alarmSheshiChartsList
            ) {
                if (Objects.nonNull(map2.get(alarmSheshiCharts.getSheshiName()).get("氨气报警"))){
                    alarmSheshiCharts.setNH4Count(map2.get(alarmSheshiCharts.getSheshiName()).get("氨气报警").size());
                }
                if (Objects.nonNull(map2.get(alarmSheshiCharts.getSheshiName()).get("烟雾报警"))){
                    alarmSheshiCharts.setSmokeCount(map2.get(alarmSheshiCharts.getSheshiName()).get("烟雾报警").size());
                }
                if (Objects.nonNull(map2.get(alarmSheshiCharts.getSheshiName()).get("硫化氢报警"))){
                    alarmSheshiCharts.setH2SCount(map2.get(alarmSheshiCharts.getSheshiName()).get("硫化氢报警").size());
                }
                if (depMap.containsKey(alarmSheshiCharts.getDepId())) {
                    alarmSheshiCharts.setDepName(depMap.get(alarmSheshiCharts.getDepId()).getDepartName());
                }
                if (facMap.containsKey(alarmSheshiCharts.getSheshiId())) {
                    alarmSheshiCharts.setSheshiType(facilitiesTypeMap.get(facMap.get(alarmSheshiCharts.getSheshiId()).getFacltypeid()).getFacilitietypename());
                }
            }
        }

        return alarmSheshiChartsList;
    }
    private  List<List<Object>> getSelectAlarmForCharts(Date startDate,Date endDate,List<AlarmSheshiCharts> bTableList) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        List<Object> resList = new ArrayList<>();
        List<List<Object>> resList2 = new ArrayList<>();
        List<String> dateStringList = new ArrayList<>();
        dateStringList = Tools.getDateList(format, startDate, endDate);
        Boolean flag = true;
        for (int i = 0; i < dateStringList.size(); i++) {
            resList.add(dateStringList.get(i));
            for (AlarmSheshiCharts c : bTableList) {
                if (dateStringList.get(i).equals(c.getAlarmTime())) {
                    flag = false;
                    resList.addAll(c.getResList());
                    resList2.add(resList);
                }
            }
            for (AlarmSheshiCharts c : bTableList) {
                if (flag) {
                    resList.add(0);
                    resList.add(0);
                    resList.add(0);
                    resList.add(0);
                    resList.add(0);
                    resList2.add(resList);
                    flag = false;
                }
            }
            resList = new ArrayList<>();
            flag = true;

        }
        return resList2;
    }

    private  List<List<Object>> getSelectAlarmForChartsByMonth(Date startDate,Date endDate,List<AlarmSheshiCharts> bTableList) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        List<Object> resList = new ArrayList<>();
        List<List<Object>> resList2 = new ArrayList<>();
        List<String> dateStringList = new ArrayList<>();

        String beginDate =  DateUtil.formatDate(startDate);
        String lastDate = DateUtil.formatDate(endDate);
        dateStringList = Tools.getMonthList(beginDate, lastDate);
        Boolean flag = true;
        for (int i = 0; i < dateStringList.size(); i++) {
            resList.add(dateStringList.get(i));
            for (AlarmSheshiCharts c : bTableList) {
                if (dateStringList.get(i).equals(c.getAlarmTime())) {
                    flag = false;
                    resList.addAll(c.getResList());
                    resList2.add(resList);
                }
            }
            for (AlarmSheshiCharts c : bTableList) {
                if (flag) {
                    resList.add(0);
                    resList.add(0);
                    resList.add(0);
                    resList.add(0);
                    resList.add(0);
                    resList2.add(resList);
                    flag = false;
                }
            }
            resList = new ArrayList<>();
            flag = true;

        }
        return resList2;
    }

    /**
     * 列表明细
     */
    @Override
    public TableDataInfo selectAlarmSheshiForTableDetail(AlarmSheshi alarmSheshi) {
        List<AlarmSheshiTableDetailVO> alarmSheshiTableDetailVOList = getAlarmSheshiTableDetailVOS(alarmSheshi);
        return Tools.buildTableDataInfo(alarmSheshi.getPageNum(), alarmSheshi.getPageSize(), alarmSheshiTableDetailVOList);
    }
    @Override
    public List<AlarmSheshiTableDetailVO> getAlarmSheshiTableDetailVOS(AlarmSheshi alarmSheshi) {
        if (Objects.isNull(alarmSheshi.getAlarmStartTime())){
            alarmSheshi.setAlarmStartTime(DateUtil.parseDateTime(DateUtil.format(new Date(), DatePattern.NORM_MONTH_PATTERN)+"-01 00:00:00"));
        } else {
            alarmSheshi.setAlarmStartTime(DateUtil.parseDateTime(DateUtil.formatDate(alarmSheshi.getAlarmStartTime()) +" 00:00:00"));
        }
        if (Objects.isNull(alarmSheshi.getAlarmEndTime())){
            alarmSheshi.setAlarmEndTime(DateUtil.parseDateTime(DateUtil.formatDate(new Date())+" 23:59:59"));
        } else {
            alarmSheshi.setAlarmEndTime(DateUtil.parseDateTime(DateUtil.formatDate(alarmSheshi.getAlarmEndTime())+" 23:59:59"));
        }
        QueryWrapper<AlarmSheshi> alarmSheshiQueryWrapper=new QueryWrapper<>();
        if (StringUtils.isNotEmpty(alarmSheshi.getSheshiId())){
            alarmSheshiQueryWrapper.lambda().eq(AlarmSheshi::getSheshiId, alarmSheshi.getSheshiId());
        }
        if (StringUtils.isNotEmpty(alarmSheshi.getSheshiName())){
            alarmSheshiQueryWrapper.lambda().eq(AlarmSheshi::getSheshiName, alarmSheshi.getSheshiName());
        }
        if (StringUtils.isNotEmpty(alarmSheshi.getAlarmTypeName())){
            alarmSheshiQueryWrapper.lambda().eq(AlarmSheshi::getAlarmTypeName, alarmSheshi.getAlarmTypeName());
        }
        if (CollectionUtils.isNotEmpty(alarmSheshi.getIds())){
            alarmSheshiQueryWrapper.lambda().in(AlarmSheshi::getAlarmSheshiId, alarmSheshi.getIds());
        }

        if (Objects.nonNull(alarmSheshi.getAlarmStartTime())) {
            alarmSheshiQueryWrapper.lambda().ge(AlarmSheshi::getAlarmTime, alarmSheshi.getAlarmStartTime());
        }
        if (Objects.nonNull(alarmSheshi.getAlarmEndTime())) {
            alarmSheshiQueryWrapper.lambda().le(AlarmSheshi::getAlarmTime, alarmSheshi.getAlarmEndTime());
        }
        alarmSheshiQueryWrapper.lambda().orderByDesc(AlarmSheshi::getAlarmTime);

        List<AlarmSheshi> alarmSheshiList = alarmSheshiMapper.selectList(alarmSheshiQueryWrapper);

        List<AlarmSheshiTableDetailVO> alarmSheshiTableDetailVOList = new ArrayList<>();
        alarmSheshiList.forEach(t -> {
            AlarmSheshiTableDetailVO alarmSheshiTableDetailVO = new AlarmSheshiTableDetailVO();
            alarmSheshiTableDetailVO.setId(t.getAlarmSheshiId());
            alarmSheshiTableDetailVO.setFacilitiesId(t.getSheshiId());
            alarmSheshiTableDetailVO.setFacilitiesName(t.getSheshiName());
            alarmSheshiTableDetailVO.setFacltypename(t.getFacltypename());
            alarmSheshiTableDetailVO.setFacltypeitemname(t.getFacltypeitemname());
            alarmSheshiTableDetailVO.setDepName(t.getDepName());
            alarmSheshiTableDetailVO.setAlarmTypeName(t.getAlarmTypeName());
            alarmSheshiTableDetailVO.setAlarmStartTime(DateUtil.formatDateTime(t.getAlarmStartTime()));
            alarmSheshiTableDetailVO.setAlarmEndTime(DateUtil.formatDateTime(t.getAlarmEndTime()));
            alarmSheshiTableDetailVO.setContent(t.getContent());
            /** 保存地址 **/
            String currentAddress = locationUtil.getAddress(t.getLng(), t.getLat());
            if (StringUtils.isNotEmpty(currentAddress)) {
                alarmSheshiTableDetailVO.setAddress(currentAddress);
            } else {
                alarmSheshiTableDetailVO.setAddress("");
            }
            alarmSheshiTableDetailVOList.add(alarmSheshiTableDetailVO);
        });
        return alarmSheshiTableDetailVOList;
    }
}
